// ==UserScript==
// @name         Gitea验证码自动识别（实时触发版）
// @namespace    your_namespace
// @version      1.4
// @description  每次聚焦输入框都触发验证码识别
// @match        https://gitea.nonex.top/*
// @grant        GM_xmlhttpRequest
// @connect      10.0.0.3
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';
    
    const API_URL = 'https://api.nonex.top/captcha/code';

    // 获取最新验证码图片（带缓存清除参数）
    function getFreshCaptchaUrl(imgElement) {
        const baseUrl = imgElement.src.split('?')[0];
        return `${baseUrl}?t=${Date.now()}`;
    }

    async function recognizeCaptcha() {
        const captchaImage = document.querySelector('img.captcha-img');
        if (!captchaImage) return;

        try {
            // 使用新的时间戳获取图片
            const freshUrl = getFreshCaptchaUrl(captchaImage);
            const base64 = await fetchImageAsBase64(freshUrl);
            const code = await requestRecognition(base64);
            
            const input = document.querySelector('input[name="captcha"]');
            if (input) {
                input.value = code;
                input.dispatchEvent(new Event('input', { bubbles: true }));
            }
        } catch(e) {
            console.error('识别失败:', e);
        }
    }

    function fetchImageAsBase64(url) {
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: "GET",
                url: url,
                responseType: "blob",
                onload: (res) => {
                    const reader = new FileReader();
                    reader.onloadend = () => resolve(reader.result.split(',')[1]);
                    reader.readAsDataURL(res.response);
                },
                onerror: reject
            });
        });
    }

    function requestRecognition(base64) {
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: "POST",
                url: API_URL,
                headers: {"Content-Type": "application/json"},
                data: JSON.stringify({ImageBase64: base64}),
                onload: (res) => {
                    const result = JSON.parse(res.responseText);
                    result.status === 'success' 
                        ? resolve(result.result) 
                        : reject(new Error('API返回错误'));
                },
                onerror: reject
            });
        });
    }

    function init() {
        const input = document.querySelector('input[name="captcha"]');
        if (!input) {
            setTimeout(init, 500);
            return;
        }

        // 每次聚焦都触发
        input.addEventListener('focus', () => {
            recognizeCaptcha();
        });
    }

    // 启动逻辑
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();